package com.im.annotation;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.im.pojoClass.Result;
import com.im.pojoClass.ResultCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class JwtService {

    @Value("${jwt.key}")
    private String JWT_KEY;

    /**
     * Around能返回什么类型，取决于加了@JWT注解方法的返回类型
     */
    @Around(value = "@annotation(com.im.annotation.Jwt)")
    public Object before_jwt(ProceedingJoinPoint pjp) {

        //获取RequestHttp
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes r = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = r.getRequest();

        String token = request.getHeader("Token");

//        System.out.println(token);

        if (token == null) {
            return new Result(ResultCode.FORBIDDEN, "缺少Token");
        }

        Object result = null;

        try {
            //检测签名私钥
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWT_KEY)).build();
            //校对token
            jwtVerifier.verify(token);

            result = pjp.proceed();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FORBIDDEN, "Token校验失败");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return new Result(ResultCode.FAILED, "系统错误");
        }
        return result;
    }
}